import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC, wait

USER_NAME = "xxxxxxxxx"
PASSWORD = "123456"

if __name__ == "__main__":
    # 由于selenium是通过driver去操作浏览器的，所以需要获取对应浏览器的driver对象
    driver = webdriver.Chrome()
    # 设置隐式等待时间
    driver.implicitly_wait(10)
    # 打开百度首页
    driver.get("http://www.iwdjy.com/user-login")
    print("打开网站成功!")
    # 定位用户名和密码输入框和输入用户名和密码
    username_input = driver.find_element(By.CSS_SELECTOR, "input[placeholder='输入用户名']")
    password_input = driver.find_element(By.CSS_SELECTOR, "input[placeholder='输入密码']")
    username_input.send_keys(USER_NAME)
    password_input.send_keys(PASSWORD)
    # 等待页面加载完成
    wait = WebDriverWait(driver, 10)
    # 点击登录
    login_button = wait.until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='button'][class='ivu-btn ivu-btn-primary']")))
    login_button.click()
    # 获取统考课程列表
    try:
        courses = driver.find_elements(By.XPATH, "//div[@id='pane-统考']/div")
        # 打印课程
        for course in courses:
            # 获取课程信息
            title = course.find_element(By.CSS_SELECTOR, ".title").text
            lecturer = course.find_element(By.CSS_SELECTOR, ".info > em:nth-child(1)").text
            # 如果需要进一步处理未完成学习的课程，可以在这里添加条件判断
            # 例如可以查找进度为0%的课程
            progress_element = course.find_element(By.CSS_SELECTOR, ".num > em > i")
            progress = progress_element.get_attribute("textContent")
            print("progress{0}".format(progress))
            if progress != "100.00%":
                print(f"课程：{title}")
                print(f"讲师：{lecturer}")
                print("尚未完成学习")
                # 滚动到元素可见
                actions = ActionChains(driver)
                actions.move_to_element(progress_element).perform()
                # 等待元素可见
                WebDriverWait(driver, 10).until(
                    EC.visibility_of_element_located((By.CSS_SELECTOR, ".jcsb > div > .study:last-child")))
                # 点击继续学习链接
                continue_link = course.find_element(By.CSS_SELECTOR, ".jcsb > div > .study:last-child")
                continue_link.click()
                time.sleep(3)

                # 使用显式等待，等待按钮可点击
                button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.el-button.jion-study")))
                # 点击按钮
                button.click()
                time.sleep(3)

                # 等待页面加载完成
                WebDriverWait(driver, 10).until(EC.url_changes(driver.current_url))
        time.sleep(100000000)
    except Exception as e:
        print(e)
    finally:
        # 关闭浏览器
        driver.quit()
